package online.yysh.charging.view;

import android.content.Context;
import android.util.AttributeSet;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatTextView;

/**
 * 获取验证码倒计时控件
 */
public class CountdownView extends AppCompatTextView implements Runnable{

    //倒计时秒数
    private int totalSecond = 60;
    //当前描述
    private int currentSecond;

    //单位：秒
    private static final String TIME_UNIT = "S";

    //原文本
    private CharSequence restoreText;

    public CountdownView(@NonNull Context context) {
        super(context);
    }

    public CountdownView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public CountdownView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public void run() {
        if (currentSecond == 0){
            stop();
        }else {
            currentSecond--;
            setText(currentSecond +" "+TIME_UNIT);
            postDelayed(this,1000);
        }
    }

    /**
     * 开始倒计时
     */
    public void start(){
        restoreText = getText();
        setEnabled(false);
        currentSecond = totalSecond;
        post(this);
    }

    /**
     * 结束倒计时
     */
    public void stop(){
        setText(restoreText);
        setEnabled(true);
    }
}
